import React, { Component } from 'react';
import Head from './Head';
import './question.css';
import Listen from './component/Listen';
import { Spin } from 'antd';
import { Modal , Toast, List, Button, WhiteSpace} from 'antd-mobile';
import { get } from '../../Lib/Http';
import apiUrl from '../../Config/web';
import Cloze from './component/Cloze';
import Match from './component/Match';
import ReadCareful from './component/ReadCareful';
import { trim } from '../../Lib/Str';
import Translation from './component/Translation';
import Writing from './component/Writing';

class Question extends Component {

    componentDidMount(){

        let that = this;

        let _b_url = that.props.history.location.pathname;
        window._hmt.push(['_trackPageview', _b_url]);

        let parmasData = this.props.match;

        get(apiUrl.eaxm, {
            id:parmasData.params.id
        },function (response) {

            //成功请求
            if(response.data.code === 0){
                let form = that.state.form;
                form['id'] = response.data.data.id;

                that.setState({
                    data:response.data.data,
                    form:form,
                    switchText:'答题',
                });
                return;
            }

            //未登录
            if(response.data.code === 1000){
                that.props.history.push('/login');
                return;
            }


            if(response.status !== 200){
                return;
            }
            
            const alert = Modal.alert;
            alert('提示', '请先购买试卷', [
                { text: '确认', onPress: () => that.props.history.goBack() },
            ]);

        }, 
        function (error) {

            if(error.response === undefined){
                return;
            }


            if(error.response.status == 401 && error.response.data.message == 'Unauthenticated.'){
                that.props.history.push('/login');
            }


        });


    }



    constructor(props){
        super(props);

        this.state = {
            switch:0,
            form:{},
            modal2: false,
            mean:{
            },
            query:false,
        };

    }

    countHeight(){
        let height = window.innerHeight;
        let result = 100-(44/height*100);
        return result+'%';
    }

    switchBorad(e){
       let switchTag = this.state.switch;

       if(switchTag === 0){
           this.setState({
               switch:1,
               switchText:'返回'
           });
       }

       if(switchTag === 1){
            this.setState({
                switch:0,
                switchText:'答题'
            });
        }

    }

    //关闭弹窗显示
    onClose = key => () => {
        this.setState({
          [key]: false,
        });
    }

    //搜索单词
    searchWord(text){

        if(this.state.query === false){
            return;
        }

        text = trim(text.innerText);
        
        let reg = /^[a-zA-Z][a-zA-Z'_-]{0,}[a-zA-Z]$/g

        if(!reg.test(text)){
            return;
        }

        Toast.loading('loading', 0);

        let that = this;

        get(apiUrl.search_word, {word:text}, function(success){
            Toast.hide();

            let data = success.data;

            //未查询到
            if(data.code == 1008){
                Toast.info('未查询到单词');
                return;
            }

            if(data.code == 0){
                
                that.setState({
                    'modal2':true,
                    'mean':data.data
                });

                console.log(data.data);
                
                return;
            }


        }, function(error){
            Toast.hide();
            console.log(error);
        })

    }

    //标记单词(用户点击单词变颜色或查询中文释义)
    markWord(e){

        let thisNode = e.target;

        if(thisNode.localName !== 'span'){
            return;
        }

        if(thisNode.className.indexOf('not-mark') > -1){
            return;
        }

        this.searchWord(thisNode);
        
        if( thisNode.className.indexOf('user-mark') > -1 ){

            let className = thisNode.className.replace(/(\suser-mark)/, '');
            
            e.target.className = className;

            return;
        }


        if(thisNode.className.indexOf('query_words') > -1){

            let className = thisNode.className+' user-mark';

            e.target.className = className;

            return
        }
    }

    //记录用户选项
    saveSelected(e){
        let thisNode = e.target;

        let name = thisNode.dataset.id;
        let value = thisNode.dataset.value;
        let form = this.state.form;
        form[name] = value;

        this.setState(
            {form:form}
        );

    }

    //提交答案
    submit(e){
        
        let form = this.state.form;

        form['type'] = this.state.data.type;

        this.props.history.push('/result', form);

    }

    //显示对话框
    showConfirm(e){

        const alert = Modal.alert;
        alert('提示', '确认交卷?', [
            { text: '取消', onPress: () => console.log('cancel'), style: 'default' },
            { text: '确认', onPress: () => this.submit(e) },
        ]);

    }

    switchQuery(bool){
        this.setState({
            query:bool
        });
    }

    render() {

        if(this.state.data === undefined){
            return (<Spin tip="Loading..." className="home-loding" size="large" />);
        }

        let bookData = this.state.data.bind_book[0];

        let width = window.innerWidth;

        //题目显示那个题目控件
        //todo:写成一个方法
        let questionType;

        if(this.state.data.type === 1){
            questionType = <Listen mark={this.markWord.bind(this)} data={this.state.data} switch={this.state.switch} width={width} height={this.countHeight()} input={this.saveSelected.bind(this)} />
        }

        if(this.state.data.type === 2 ){
            questionType = <Cloze mark={this.markWord.bind(this)} data={this.state.data} switch={this.state.switch} width={width} height={this.countHeight()} input={this.saveSelected.bind(this)} />
        }


        if(this.state.data.type === 3){
            questionType = <Match mark={this.markWord.bind(this)} data={this.state.data} switch={this.state.switch} width={width} height={this.countHeight()} input={this.saveSelected.bind(this)} />
        }

        if(this.state.data.type === 4){
            questionType = <ReadCareful mark={this.markWord.bind(this)} data={this.state.data} switch={this.state.switch} width={width} height={this.countHeight()} input={this.saveSelected.bind(this)} />
        }

        if(this.state.data.type === 5){
            questionType = <Translation mark={this.markWord.bind(this)}  data={this.state.data} switch={this.state.switch} width={width} height={this.countHeight()} input={this.saveSelected.bind(this)}/>
        }

        if(this.state.data.type === 6){
            questionType = <Writing mark={this.markWord.bind(this)}  data={this.state.data} switch={this.state.switch} width={width} height={this.countHeight()} input={this.saveSelected.bind(this)}/>
        }


        return (
            <div className="root">

                <Modal popup visible={this.state.modal2}  onClose={this.onClose('modal2')} animationType="slide-up">
                   <div style={{height:300}}>
                       <div className="ws-wrapper">
                            <div className="ws-word">
                                {this.state.mean.word}
                            </div>
                            <ul className="ws-phonetic-box">
                                <li className="ws-us">
                                    <i className="icon iconfont icon-shengyin ws-sy"></i>
                                    美 
                                    <rt dangerouslySetInnerHTML={{__html:this.state.mean['us_pronounce']}}></rt>
                                </li>
                                <li className="ws-un">
                                    <i className="icon iconfont icon-shengyin ws-sy"></i>
                                    英 
                                    <rt dangerouslySetInnerHTML={{__html:this.state.mean['un_pronounce']}}></rt>
                                </li>
                            </ul>
                            <div style={{clear:'both'}}></div>
                            <ul className="ws-mean" dangerouslySetInnerHTML={{__html:this.state.mean['mean']}} >
                            </ul>
                            <WhiteSpace/>
                       </div>
                   </div>
                </Modal>

                <Head url={'/detail/'+bookData.id} history={this.props.history} submit={this.showConfirm.bind(this)} query={this.switchQuery.bind(this)} />
                {questionType}
                <div onClick={(e)=>this.switchBorad(e)} className="switch">
                   <div className="switch-text">{this.state.switchText}</div>
                </div>
            </div>
        );
    }
}

export default Question;